package cn.school.servlet.filter;

import cn.school.entity.Subject;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;

/**
 * @author oldliu
 * @since 1.0
 */
//拦截所有的地址
//统计每个请求的执行时间
@WebFilter(filterName = "timeFilter", value = "/*")
public class TimeFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("进入了TimeFilter，时间是:"+new Date());
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        request.setCharacterEncoding("utf-8");//gbk
        String path=request.getServletPath();//请求地址
        long start=System.nanoTime();//开始

        filterChain.doFilter(request,servletResponse);//!!!!!! 下一个资源

        long end= System.nanoTime();

        System.out.println("请求"+path+" 耗费时间"+(end-start)+"纳秒");

        System.out.println("离开了TimeFilter，时间是:"+new Date());
    }

    @Override
    public void destroy() {

    }
}
